import React, { Component } from 'react';
import {
  Text,
  View,
  Dimensions,
  Vibration,
  Animated,
  Easing,
  Alert,
  StyleSheet,
  TouchableOpacity,
} from 'react-native';
import Camera from 'react-native-camera';
import NavBar from './NavigatorBar';
import { Actions } from 'react-native-router-flux';
import * as defaulStyles from '../constants/DefaultStyles';
import prompt from 'react-native-prompt-android';
import { requestXML } from '../utils/RequestUtils';
import { json2xml_str } from '../utils/XmlUtils';
import Spinner from 'react-native-loading-spinner-overlay';


function removeThousand(str) {
  return str.replace(/,/g, '');
}

export default class ScanQRCode extends Component {

  constructor(props){
    super(props) ;
    this.state={
      scanTranslte:new Animated.Value(0),
      getQRinfo: false,
      isLoading: false,
      textContent: '',
    }
  }
  componentDidMount(){

    this.scanLineAnimation();
  }
  scanLineAnimation(){
    Animated.sequence([
      Animated.timing(this.state.scanTranslte,{toValue:250 , duration:2000 , easing:Easing.linear}),
      Animated.timing(this.state.scanTranslte,{toValue:0 , duration:2000 , easing:Easing.linear})
    ]).start(()=>this.scanLineAnimation()) ;
  }
  // componentWillUnmout(){
  //   this.camera&&this.camera.shouldQR();
  // }
  onBarCodeRead(result){

    // if(this.props.onBarCodeRead)
    // {
    //   this.props.onBarCodeRead(result , ()=>{this.camera.shouldQR();});
    // }
    // else {
    //   Alert.alert( "扫描结果" , result.data , [{text:"ok" , onPress:()=>this.camera&&this.camera.shouldQR()}] , {cancelable:false});
      if (!this.state.getQRinfo) {
        Vibration.vibrate();
        this.state.getQRinfo = true;
        this._fetchWithQRinfo(result.data, "扫描成功，等待收款结果");
      }
    // }



  }
  _leftClick() {
    Actions.pop();
  }
  _fetchWithQRinfo(QRInfo, textContent) {
    this.setState({textContent: textContent, isLoading: true});
    let xml = json2xml_str(JSON.stringify({
      Request: {
        Head: {
          trace_no: '6',
          terminalno: '8',
          acceptidcode: merid,
          tanstype: '80003',
          operateno: '3'
        },
        Body: {
          amt: this.props.value,
          amtcd: 'CNY',
          batchno: '6',
          QRinfo: QRInfo,
          tellerno: '3',
          mac: '32',
          SIGN: '122',
          payType: QRInfo.substring(0, 2),
        }}
    }));
    let respcd = '-1';
    const promise = requestXML('http://192.168.1.112:8080/icmp-ums/dhc/sys/mobile.do', xml, 20000);
    promise.then((object) => {
        console.log(object);
        let Body = object.Response.Body;
        if (Body.respcd === '-1') {
          Alert.alert('提示', '请求超时，请检查网络连接', [{text: '确定', onPress: () => {this.state.getQRinfo = false, this.setState({isLoading: false})}}]);
          return;
        }

        try {
          respcd = Body.respcd;
        }
        catch (err) {
          alert('返回数据出错');
        }

        if (respcd === '00') {
          Alert.alert('提示', '收款成功', [{text: '确定', onPress: () => {this.setState({isLoading: false}), Actions.pop()}}])
        }
        else {
          Alert.alert('提示', respcd, [{text: '确定', onPress: () => {this.state.getQRinfo = false, this.setState({isLoading: false})}}])
          return;
        }
      },(reject) => {
        console.log(reject);
        // try{
        //   if (reject.state === "-1") {
        //     Alert.alert('提示', '请求超时，请检查网络连接', [{text: '确定', onPress: () => {this.state.getQRinfo = false, this.setState({isLoading: false})}}]);
        //     return;
        //   }
        // }
        // catch (e) {
          Alert.alert('提示', '请求失败，请检查网络连接', [{text: '确定', onPress: () => {this.state.getQRinfo = false, this.setState({isLoading: false})}}]);
        // }
      }
    );
  }
  _getQRCode(type) {
    let tanstype = '80014'
    if (type === 'alipay') {
      tanstype = '80008';
    }
    this.setState({textContent: '', isLoading: true});
    console.log(this.state.code);
    let xml = json2xml_str(JSON.stringify({
      Request: {
        Head: {
          trace_no: '6',
          terminalno: '8',
          acceptidcode: merid,
          tanstype: tanstype,
          operateno: '3'
        },
        Body: {
          SIGN: '122',
          amt: String(parseFloat(removeThousand(this.props.amout)) * 100)
        }}
    }));
    let respcd = '-1';
    const promise = requestXML('http://192.168.4.13:8084/icmp-ums/dhc/sys/mobile.do', xml, 15000);
    promise.then((object) => {
      console.log(object);
      let respcd = '-1';
      try {
        let Body = object.Response.Body;
        respcd = Body.respcd;
        if (respcd === '00') {
          this.setState({isLoading: false});
          if (type === 'wechat') {
            let QRValue = Body.code_url;
            Actions.createQRCode({
              title: '微信支付收款',
              amout: this.props.amout,
              QRCodeValue: QRValue,
              paymentType: '2',
              type: 'replace'
            });
          }
          else if (type === 'alipay') {
            let QRValue = Body.qr_code;
            Actions.createQRCode({
              title: '支付宝收款',
              amout: this.props.amout,
              QRCodeValue: QRValue,
              paymentType: '1',
              type: 'replace'})
          }
        }
        else {
          Alert.alert('提示', '获取二维码失败', [{text: '确定', onPress: () => {this.setState({isLoading: false})}}]);
          return;
        }
      }
      catch (err) {
        Alert.alert('提示', '返回数据格式出错', [{text: '确定', onPress: () => {this.setState({isLoading: false})}}]);
      }
    }, (reject) => {
      Alert.alert('提示', '请求出错，请检查网络连接', [{text: '确定', onPress: () => {this.setState({isLoading: false})}}]);
    });
  }
  render() {
    let width = defaulStyles.SCREENWIDTH;
    let height = defaulStyles.SCREENHEIGHT;
    let scanCoverColor = '#44444488';
    let scanRectWidth = 250;
    return (
      <View style={styles.container}>
        <Spinner visible={this.state.isLoading} overlayColor={'rgba(0, 0, 0, 0.7)'}
                 textContent={this.state.textContent} textStyle={{color: 'white'}}/>
        <Camera
          style={{width:width , height:height}}
          type={Camera.constants.Type.back}
          ref={(cam) => {
            this.camera = cam;
          }}
          onBarCodeRead={this.onBarCodeRead.bind(this)}
        />
        <View
          style={styles.scanContainer}
        >
          <NavBar leftImage="angle-left" navBarColor={scanCoverColor}
                  leftClick={this._leftClick.bind(this)} title="扫一扫"/>
          <View style={styles.amout}>
            <Text style={{fontSize: 18, color: 'white'}}>{'￥' + this.props.amout}</Text>
          </View>
          <View style={{width:width , height:scanRectWidth ,flexDirection:'row'}}>
            <View style={{flex:1,backgroundColor:scanCoverColor}}/>
            <View style={{width:scanRectWidth}}>
              <Animated.View style={{width:scanRectWidth , height:2 , backgroundColor:"#1dacf9" , transform:[
                                     {translateY:this.state.scanTranslte}
                                   ] }}/>
            </View>
            <View style={{flex:1 , backgroundColor:scanCoverColor}}/>
          </View>
          <View style={styles.note}>
            <Text style={{color: 'white', fontSize: 13}}>讲顾客付款码放入输入框中，即可自动扫描</Text>
          </View>
          <View style={styles.changePayment}>
            <TouchableOpacity onPress={() => this._getQRCode('alipay')}>
              <Text style={{fontSize: 15, color: defaulStyles.LIGHTBLUE}}>切换二维码收款</Text>
            </TouchableOpacity>
            <Text style={{fontSize: 15, color: defaulStyles.LIGHTBLUE}}>{' | '}</Text>
            <TouchableOpacity onPress={() =>
                prompt(
                  '',
                  '输入付款码',
                  [
                   {text: '取消', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
                   {text: '确定', onPress: value => this._fetchWithQRinfo(value, "等待收款结果")},
                  ],
                  {
                      cancelable: false,
                      defaultValue: '',
                      placeholder: ''
                  })
            }>
              <Text style={{fontSize: 15, color: defaulStyles.LIGHTBLUE}}>输入付款码</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  scanContainer: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
  },
  amout: {
    width: defaulStyles.SCREENWIDTH,
    height: 90,
    paddingTop: 20,
    alignItems: 'center',
    backgroundColor: '#44444488',
  },
  note: {
    width: defaulStyles.SCREENWIDTH,
    height: 100,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#44444488',
  },
  changePayment: {
    flex: 1,
    flexDirection: 'row',
    width: defaulStyles.SCREENWIDTH,
    justifyContent: 'center',
    backgroundColor:'#44444488',
  }
});